package com.system.dao.impl;

import java.sql.ResultSet;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;

import com.system.dao.UserDao;
import com.system.model.User;
import com.system.util.JdbcUtil;
import com.system.util.ResultMapUtil;

public class UserDaoImpl extends BaseDaoImpl implements UserDao {

	public UserDaoImpl() throws Exception {
		super();
	}
	
	/**
	 * 对查找的重复操作进行封装
	 * @return
	 */
	private User find(String sql){
		try{
			ResultSet rs=this.templateQuery(sql);
			User user=new User();
			if(rs.next()){
				Map<String,String> map=ResultMapUtil.getResultMap(rs);
				try{
					BeanUtils.populate(user, map);
				}catch(Exception e){
					e.printStackTrace();
				}
			}
			else {
				return null;
			}
			//如果还有记录，说明名字有重复，向上抛出异常
			if(rs.next())
				throw new Exception("you have a repeated user");
			else 
				return user;
				
		}catch(Exception e){
			e.printStackTrace();
		}
		return null;
	}
	
	@Override
	public User findByNamePsd(String username, String password) {
		String sql="select * from "+"user"+" where username="+"'"+username+"'"
				+" and password="+"'"+password+"'";
		User user=find(sql);
		JdbcUtil.getInstance().free(conn);
		return user;
	}

	@Override
	public User findByUsername(String username) throws Exception {
		String sql="select * from "+"user"+" where username="+"'"+username+"'";
		User user=find(sql);
		JdbcUtil.getInstance().free(conn);
		return user;
	}

	@Override
	public boolean add(User user) {
		User u = this.findByNamePsd(user.getUsername(), user.getPassword());
		//if user exist.
		if(u != null && u.getPost().equals(user.getPost())) {
			return false;
		}
		String sql="insert into "+"user"+" (username,password"
				+ ",post)"+"values"+"("+
				"'"+user.getUsername()+"'"+
				","+"'"+user.getPassword()+"'"+","
				+"'"+user.getPost()+"'"+")";
		try{
			this.templateUpdate(sql);
			System.out.println(sql);
			return true;
		}
		catch(Exception e){
			e.printStackTrace();
		}
		finally{
			JdbcUtil.getInstance().free(conn);
		}
		return false;
	}

	@Override
	public boolean deleteUser(String username) {
		try{
			String sql="delete from "+"user"+" where username="+"'"+username+"'";
			this.templateUpdate(sql);
			return true;
		}
		catch(Exception e){
			e.printStackTrace();
		}
		finally{
			JdbcUtil.getInstance().free(conn);
		}
		return false;
	}

	@Override
	public boolean modify(User user) {
		String sql="update user set username="+"'"+user.getUsername()+"'"+","
				+ " password="+"'"+user.getPassword()+"'"+","
				+" post="+"'"+user.getPost()+"'"
				+" where username="+"'"+user.getUsername()+"'";
		try{
			this.templateUpdate(sql);
			return true;
		}
		catch(Exception e){
			e.printStackTrace();
		}
		finally{
			JdbcUtil.getInstance().free(conn);
		}
		return false;
	}
}
